/**
 * 
 */
package com.gmail.avereshchaga.web.controller;

import static com.gmail.avereshchaga.tools.Command.DIVISION_CREATE_COMMAND;
import static com.gmail.avereshchaga.tools.Command.DIVISION_UPDATE_COMMAND;
import static com.gmail.avereshchaga.tools.UrlList.DIVISION_CREATE_URL;
import static com.gmail.avereshchaga.tools.UrlList.DIVISION_LIST_URL;
import static com.gmail.avereshchaga.tools.UrlList.DIVISION_UPDATE_URL;
import static com.gmail.avereshchaga.tools.ViewList.DIVISION_CREATE_VIEW;
import static com.gmail.avereshchaga.tools.ViewList.DIVISION_LIST_VIEW;
import static com.gmail.avereshchaga.tools.ViewList.DIVISION_UPDATE_VIEW;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.gmail.avereshchaga.db.entity.DivisionImpl;
import com.gmail.avereshchaga.db.entity.IDivision;
import com.gmail.avereshchaga.db.service.IDivisionService;
import com.gmail.avereshchaga.web.controller.ServiceFunction;
import com.gmail.avereshchaga.web.form.DivisionForm;

/**
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 * 
 */
@Controller
public class DivisionController {

    @Autowired
    private IDivisionService divisionService;

    /**
     * Выбирает все записи отделов из БД и выводит их на страницу
     * 
     * @return ModelAndView
     */
    @RequestMapping(value = DIVISION_LIST_URL, method = RequestMethod.GET)
    public ModelAndView findAll() {
        Map<String, Object> model = new HashMap<String, Object>();
        List<IDivision> divisions = divisionService.findAll();
        Collections.sort(divisions, ServiceFunction.SENIORITY_ORDER_DIVISION);
        model.put("divisions", divisions);
        return new ModelAndView(DIVISION_LIST_VIEW, model);
    }

    /**
     * Выводит на страницу форму создания отдела
     * 
     * @return ModelAndView
     */
    @RequestMapping(value = DIVISION_CREATE_URL, method = RequestMethod.GET)
    public ModelAndView create() {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(DIVISION_CREATE_COMMAND, new DivisionForm());
        return new ModelAndView(DIVISION_CREATE_VIEW, model);
    }

    /**
     * Сохраняет новый отдел
     * 
     * @param divisionForm
     * @param result
     * @return ModelAndView
     */
    @RequestMapping(value = DIVISION_CREATE_URL, method = RequestMethod.POST)
    public ModelAndView create(
            @Valid @ModelAttribute(DIVISION_CREATE_COMMAND) DivisionForm divisionForm,
            BindingResult result) {

        if (result.hasErrors()) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put(DIVISION_CREATE_COMMAND, new DivisionForm());
            return new ModelAndView(DIVISION_CREATE_VIEW, model);
        }

        DivisionImpl division = new DivisionImpl();
        division.setName(divisionForm.getName().trim());
        divisionService.createDivision(division);
        return new ModelAndView("redirect:../" + DIVISION_LIST_URL);
    }

    /**
     * Выводит на страницу форму для редактирования отдела
     * 
     * @param id
     * @return ModelAndView
     */
    @RequestMapping(value = DIVISION_UPDATE_URL + "/{id}", method = RequestMethod.GET)
    public ModelAndView update(@PathVariable("id") Long id) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(DIVISION_UPDATE_COMMAND, divisionService.readDivision(id));
        return new ModelAndView(DIVISION_UPDATE_VIEW, model);
    }

    /**
     * Редактирует отдел
     * 
     * @param divisionForm
     * @param result
     * @return ModelAndView
     */
    @RequestMapping(value = DIVISION_UPDATE_URL + "/{id}", method = RequestMethod.POST)
    public ModelAndView update(
            @Valid @ModelAttribute(DIVISION_UPDATE_COMMAND) DivisionForm divisionForm,
            BindingResult result) {
        if (result.hasErrors()) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put(DIVISION_UPDATE_COMMAND, new DivisionForm());
            return new ModelAndView(DIVISION_UPDATE_VIEW, model);
        }
        DivisionImpl division = (DivisionImpl) divisionService
                .readDivision(divisionForm.getId());
        division.setName(divisionForm.getName());
        divisionService.updateDivivsion(division);
        return new ModelAndView("redirect:../../" + DIVISION_LIST_URL);
    }

    /**
     * @return the divisionService
     */
    public IDivisionService getDivisionService() {
        return divisionService;
    }

    /**
     * @param divisionService the divisionService to set
     */
    public void setDivisionService(IDivisionService divisionService) {
        this.divisionService = divisionService;
    }

}
